<?php

namespace MLM\Controller;

use Zend\View\Model\ViewModel;
use Zend\Authentication\Result;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Adapter\DbTable as AuthAdapter;

class ExcelController extends \MLM\Model\Generic\Controller
{
    

    public function indexAction()
    {
        //
    }

    

    public function weeklybalanceAction()
    {

        set_time_limit( 0 );

        $date1 = (isset($this->param['date1'])) ? str_replace('-', '', $this->param['date1']) : date('Ymd', mktime(0, 0, 0, date("m")  , date("d")-7, date("Y")));
        $date2 = (isset($this->param['date2'])) ? str_replace('-', '', $this->param['date2']) : date('Ymd');

        $sn = (isset($this->param['sn'])) ? $this->param['sn'] : "";


        $this->admin = new Application_Model_Admin();
        $data = $this->admin->getWeeklyBalance($sn, $date1, $date2, "", "");

        //print_r($data);
        //die();
        $file = "saldo-member-" . date( "YmdHis" ) . ".xls";
        $filename = APPLICATION_PATH . "/../public/xls/".$file;

        $realPath = realpath($filename);

        if ( false === $realPath )
        {
            touch( $filename );
            chmod( $filename, 0777 );
        }

        $filename = realpath($filename);
        $handle = fopen($filename, "w");
        

        //echo "<pre>";
        //print_r($data);

        $finalData[] = array(
                    utf8_decode("No"),
                    utf8_decode("Member Code"),
                    utf8_decode("Member Name"),
                    utf8_decode("Bank Name"),
                    utf8_decode("Rekening Bank"),
                    utf8_decode("Saldo")
            );

        $no = 0;
        foreach ($data AS $row)
        {
            $no++;
            $finalData[] = array(
                    utf8_decode($no),
                    utf8_decode($row["member_code"]), // For chars with accents.
                    utf8_decode($row["member_name"]),
                    utf8_decode($row["bank_name"]),
                    utf8_decode($row["bank_acc_num"]),
                    utf8_decode($row["balance"])
            );
        }

        foreach ( $finalData AS $finalRow )
        {
            fputcsv( $handle, $finalRow, "\t" );
        }

        fclose( $handle );


        //print_r($finalData);
        //die();

        /*
        $this->getResponse()->setRawHeader( "Content-Type: application/vnd.ms-excel; charset=UTF-8" )
        ->setRawHeader( "Content-Disposition: attachment; filename=$file" )
        ->setRawHeader( "Content-Transfer-Encoding: binary" )
        ->setRawHeader( "Expires: 0" )
        ->setRawHeader( "Cache-Control: must-revalidate, post-check=0, pre-check=0" )
        ->setRawHeader( "Pragma: public" )
        ->setRawHeader( "Content-Length: " . filesize( $filename ) )
        ->sendResponse();
         *
         */

        //readfile( $filename );
        echo $file;
        

    }
    
    
    public function withdrawreportAction()
    {

        set_time_limit( 0 );

        $date1 = (isset($this->param['date1'])) ? str_replace('-', '', $this->param['date1']) : date('Ymd', mktime(0, 0, 0, date("m")  , date("d")-7, date("Y")));
        $date2 = (isset($this->param['date2'])) ? str_replace('-', '', $this->param['date2']) : date('Ymd');

        $sn = (isset($this->param['sn'])) ? $this->param['sn'] : "";
        $stts = (isset($this->param['stts'])) ? $this->param['stts'] : "";


        $this->admin = new Application_Model_Admin();
        $data = $this->admin->getWithdrawReport($sn, $stts, $date1, $date2, "", "");

        //print_r($data);
        //die();
        $file = "laporan-penarikan-" . date( "YmdHis" ) . ".xls";
        $filename = APPLICATION_PATH . "/../public/xls/".$file;

        $realPath = realpath($filename);

        if ( false === $realPath )
        {
            touch( $filename );
            chmod( $filename, 0777 );
        }

        $filename = realpath($filename);
        $handle = fopen($filename, "w");
        

        //echo "<pre>";
        //print_r($data);

        $finalData[] = array(
                    utf8_decode("No"),
                    utf8_decode("Tanggal"),
                    utf8_decode("Member Code"),
                    utf8_decode("Jumlah Penarikan"),
                    utf8_decode("Ditransfer Ke"),
                    utf8_decode("Status")
            );

        $no = 0;
        foreach ($data AS $row)
        {
            $no++;
            $finalData[] = array(
                    utf8_decode($no),
                    utf8_decode($row["trans_dtm"]), // For chars with accents.
                    utf8_decode($row["member_code"]),
                    utf8_decode($row["amt1"]),
                    utf8_decode($row["bank_name"]),
                    utf8_decode($row["status"])
            );
        }

        foreach ( $finalData AS $finalRow )
        {
            fputcsv( $handle, $finalRow, "\t" );
        }

        fclose( $handle );


        
        echo $file;
        

    }
    
    
    public function rewardreportAction()
    {

        set_time_limit( 0 );

        $date1 = (isset($this->param['date1'])) ? str_replace('-', '', $this->param['date1']) : date('Ymd', mktime(0, 0, 0, date("m")  , date("d")-7, date("Y")));
        $date2 = (isset($this->param['date2'])) ? str_replace('-', '', $this->param['date2']) : date('Ymd');

        $date1 = substr($date1, 0, -2);
        $date2 = substr($date2, 0, -2);
        
        $sn = (isset($this->param['sn'])) ? $this->param['sn'] : "";
        $reward = (isset($this->param['reward'])) ? $this->param['reward'] : "";

        $this->admin = new Application_Model_Admin();
        $data = $this->admin->getRewardReport($sn, $reward, $date1, $date2, "", "");

        //print_r($data);
        //die();
        $file = "laporan-reward-" . date( "YmdHis" ) . ".xls";
        $filename = APPLICATION_PATH . "/../public/xls/".$file;

        $realPath = realpath($filename);

        if ( false === $realPath )
        {
            touch( $filename );
            chmod( $filename, 0777 );
        }

        $filename = realpath($filename);
        $handle = fopen($filename, "w");
        

        //echo "<pre>";
        //print_r($data);

        $finalData[] = array(
                    utf8_decode("No"),
                    utf8_decode("Tanggal"),
                    utf8_decode("Member Code"),
                    utf8_decode("Nama Reward"),
                    utf8_decode("Reward")
            );

        $no = 0;
        foreach ($data AS $row)
        {
            $no++;
            $finalData[] = array(
                    utf8_decode($no),
                    utf8_decode($row["period"]), // For chars with accents.
                    utf8_decode($row["member_code"]),
                    utf8_decode($row["reward_name"]),
                    utf8_decode($row["descr"])
            );
        }

        foreach ( $finalData AS $finalRow )
        {
            fputcsv( $handle, $finalRow, "\t" );
        }

        fclose( $handle );


        
        echo $file;
        

    }

    public function pertumbuhanbonusAction()
    {

        set_time_limit( 0 );

        $jenis = (isset($this->param['jenis'])) ? $this->param['jenis'] : "";
        $date1 = (isset($this->param['date1'])) ? str_replace('-', '', $this->param['date1']) : date('Ymd', mktime(0, 0, 0, date("m")  , date("d")-7, date("Y")));
        $date2 = (isset($this->param['date2'])) ? str_replace('-', '', $this->param['date2']) : date('Ymd');

        $admin = new Application_Model_Admin();
        $data = $admin->getPertumbuhanBonus($jenis, $date1, $date2, "", "");

        //print_r($data);
        //die();
        $file = "pertumbuhan-bonus-" . date( "YmdHis" ) . ".xls";
        $filename = APPLICATION_PATH . "/../public/xls/".$file;

        $realPath = realpath($filename);

        if ( false === $realPath )
        {
            touch( $filename );
            chmod( $filename, 0777 );
        }

        $filename = realpath($filename);
        $handle = fopen($filename, "w");


        //echo "<pre>";
        //print_r($data);

        $finalData[] = array(
                    utf8_decode("No"),
                    utf8_decode("Tanggal"),
                    utf8_decode("Jenis Bonus"),
                    utf8_decode("Jumlah Bonus"),
                    utf8_decode("Sisa Bonus")
            );

        $no = 0;
        foreach ($data AS $row)
        {
            $no++;
            $finalData[] = array(
                    utf8_decode($no),
                    utf8_decode($row["period"]), // For chars with accents.
                    utf8_decode($row["jenis"]),
                    utf8_decode(str_replace(",","",$row["total_bonus"])),
                    utf8_decode(str_replace(",","",$row["sisa_bonus"]))
            );
        }

        foreach ( $finalData AS $finalRow )
        {
            fputcsv( $handle, $finalRow, "\t" );
        }

        fclose( $handle );



        echo $file;


    }


    public function cetaksnAction()
    {
        $identity = $this->hasSession();
        
        set_time_limit( 0 );

        $getParams = $this->getRequest()->getQuery();

        $num = (isset($getParams['num'])) ? $getParams['num'] : "";

        $db = $this->_db;
        $conn = $db->getDriver()->getConnection();

        $storage = new \MLM\Model\Sn\Storage($db);
        $data = $storage->getSN(1, "", "", "", "");


        $file = "cetak-sn-" . date( "YmdHis" ) . ".xls";
        $filename = APPLICATION_PATH . "/../public/xls/".$file;

        $realPath = realpath($filename);

        if ( false === $realPath )
        {
            touch( $filename );
            chmod( $filename, 0777 );
        }

        $filename = realpath($filename);
        $handle = fopen($filename, "w");


        //echo "<pre>";
        //print_r($data);

        $finalData[] = array(
                    utf8_decode("No"),
                    utf8_decode("SN"),
                    utf8_decode("PIN")
            );

        $no = 0;
        $snx = "";


        foreach ($data AS $row)
        {
            $no++;
            $finalData[] = array(
                    utf8_decode($no),
                    utf8_decode($row["SN"]), // For chars with accents.
                    utf8_decode($row["PIN"])
            );

            $snx .= "'".$row["SN"]."',";

        }

        if ($snx != ""){
            $conn->beginTransaction();
            $snx = substr($snx, 0, -1);
            $updateSN = $storage->updateStatusSN($snx, "1");

            if(!$updateSN){
                $conn->rollback();

                $view = new ViewModel();
                $view->setTerminal(true);
                $view->setVariable('data', 'Cetak SN Gagal');
                return $view;

            }

            $conn->commit();
            foreach ( $finalData AS $finalRow )
            {
                fputcsv( $handle, $finalRow, "\t" );
            }

            fclose( $handle );

            $view = new ViewModel();
            $view->setTerminal(true);
            $view->setVariable('data', $file);
            return $view;
        }        
    }


    public function memberpasifAction()
    {

        set_time_limit( 0 );
        $sn = (isset($this->param['sn'])) ? $this->param['sn'] : "";

        $member = new Application_Model_Member();
        $data = $member->getMemberPasif($sn, "", "");

        $file = "member-pasif-" . date( "YmdHis" ) . ".xls";
        $filename = APPLICATION_PATH . "/../public/xls/".$file;

        $realPath = realpath($filename);

        if ( false === $realPath )
        {
            touch( $filename );
            chmod( $filename, 0777 );
        }

        $filename = realpath($filename);
        $handle = fopen($filename, "w");

        $finalData[] = array(
                    utf8_decode("No"),
                    utf8_decode("Member Code"),
                    utf8_decode("Nama"),
                    utf8_decode("Alamat"),
                    utf8_decode("HP")
            );

        $no = 0;
        $snx = "";

        foreach ($data AS $row)
        {
            $no++;
            $finalData[] = array(
                    utf8_decode($no),
                    utf8_decode($row["member_code"]), // For chars with accents.
                    utf8_decode($row["member_name"]),
                    utf8_decode($row["alamat"]),
                    utf8_decode($row["mobile_no"])
            );

            
        }

        
        foreach ( $finalData AS $finalRow )
        {
            fputcsv( $handle, $finalRow, "\t" );
        }

        fclose( $handle );
        echo $file;
    }


    public function roreportAction()
    {

        set_time_limit( 0 );

        $date1 = (isset($this->param['date1'])) ? str_replace('-', '', $this->param['date1']) : date('Ymd', mktime(0, 0, 0, date("m")  , date("d")-7, date("Y")));
        $date2 = (isset($this->param['date2'])) ? str_replace('-', '', $this->param['date2']) : date('Ymd');

        $sn = (isset($this->param['sn'])) ? $this->param['sn'] : "";
        $stts = (isset($this->param['stts'])) ? $this->param['stts'] : "3";

        $admin = new Application_Model_Admin();
        $data = $admin->getROReport($sn, $stts, $date1, $date2, "", "");

        $file = "laporan-ro-" . date( "YmdHis" ) . ".xls";
        $filename = APPLICATION_PATH . "/../public/xls/".$file;

        $realPath = realpath($filename);

        if ( false === $realPath )
        {
            touch( $filename );
            chmod( $filename, 0777 );
        }

        $filename = realpath($filename);
        $handle = fopen($filename, "w");

        $finalData[] = array(
                    utf8_decode("No"),
                    utf8_decode("SN"),
                    utf8_decode("Nama"),
                    utf8_decode("Alamat"),
                    utf8_decode("Tanggal RO")
            );

        $no = 0;
        $snx = "";

        foreach ($data AS $row)
        {
            $no++;
            $finalData[] = array(
                    utf8_decode($no),
                    utf8_decode($row["member_code"]), // For chars with accents.
                    utf8_decode($row["member_name"]),
                    utf8_decode($row["addr"]),
                    utf8_decode($row["trans_dtm"])
            );


        }


        foreach ( $finalData AS $finalRow )
        {
            fputcsv( $handle, $finalRow, "\t" );
        }

        fclose( $handle );
        echo $file;
    }


    private function hasSession() {
        $auth = new AuthenticationService();

        if (!$auth->hasIdentity()) {
            return $this->redirect()->toRoute('application/default', array('controller' => 'Index', 'action' => 'login'));
        } else {
            return $auth->getIdentity();
        }
    }
    
}

